#include "Communicate.h"
#include "ProtocolMCU.h"
#include "ProtocolPC.h"

#ifdef POD_IS_205
#include "ProtocolPod205.h"
#else
#include "ProtocolPod613.h"
#endif //#ifdef POD_IS_205

#include "SerialPortPosix.h"
#include "UDPSockPosix.h"

std::map<int, ProtocolBasePosix*> protocolMap;

bool CommInitPosix()
{
#ifndef MCU_COMM_TYPE_IS_QT
    static SerialPortPosix commMCU(DEV_NAME_MCU);

    if(!commMCU.Open())
    {
        return false;
    }
    if(!commMCU.SetOpt(B19200,0,8,1,'N'))
    {
        printf("Set Port failed\n");
        return false;
    }
    ProtocolMCU::GetInstance().SetCommTool(&commMCU);
    protocolMap[commMCU.GetFd()] = &ProtocolMCU::GetInstance();
    ProtocolMCU::GetInstance().CycleSendThread();
#endif//#ifndef MCU_COMM_TYPE_IS_QT


#ifdef PC_IS_ALIVE
#ifndef PC_COMM_TYPE_IS_QT
#ifdef PC_COMM_IS_SER
    static SerialPortPosix commPC(DEV_NAME_PC);
    if(!commPC.Open()) //打开串口，返回文件描述符,上位机串口
    {
        return false;
    }
    if(!commPC.SetOpt(B115200,0,8,1,'E'))
    {
        printf("Set Port failed\n");
        return false;
    }
#else
//    static UDPSockPosix commPC(NET_PORT_PC);
    static std::shared_ptr<UDPSockPosix> commPC = std::make_shared<UDPSockPosix>(NET_PORT_PC);
    if(!commPC->Open())
    {
        return false;
    }
    //    ProtocolPC::GetInstance().SetCommTool(&commPC);
    //    protocolMap[commPC.GetFd()] = &ProtocolPC::GetInstance();
#endif //PC_COMM_IS_SER
    ProtocolPC::GetInstance().SetCommTool(commPC);
    protocolMap[commPC->GetFd()] = &ProtocolPC::GetInstance();
    ProtocolPC::GetInstance().CycleSendThread();
#endif //#ifndef PC_COMM_TYPE_IS_QT
#endif //#ifdef PC_IS_ALIVE


#ifndef POD_COMM_TYPE_IS_QT
    static SerialPortPosix commPod(DEV_NAME_POD);
    if(!commPod.Open()) //打开串口，返回文件描述符,613串口
    {
        return false;
    }
    if(!commPod.SetOpt(B115200,0,8,1,'E'))
    {
        printf("Set Port failed\n");
        return false;
    }
    ProtocolPod::GetInstance().SetCommTool(&commPod);
    protocolMap[commPod.GetFd()] = &ProtocolPod::GetInstance();
    ProtocolPod::GetInstance().CycleSendThread();
#endif//#ifndef POD_COMM_TYPE_IS_QT



//        for(auto &value : protocolMap)
//        {
//            value.second->CycleSendThread();
//        }

//    ProtocolMCU::GetInstance().CycleSendThread();
//#ifdef PC_IS_ALIVE
//    ProtocolPC::GetInstance().CycleSendThread();
//#endif
//    ProtocolPod::GetInstance().CycleSendThread();

    return true;
}
